﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.Threading;
using System.Globalization;
using System.Text.RegularExpressions;
namespace SalaryChannel
{
    public partial class App : Application
    {

       // public static Dictionary<string, object> Session = new Dictionary<string, object>();
        public static SalaryChannel.SCUserService.UserInfoEntity CurrentUser = null;
        public static MessageBox MessageBox = new MessageBox();

        public static float AssignmentPercent = 0.9F;

        public static bool IsRunning = false;
          
        public App()
        {
            this.Startup += this.Application_Startup;
            this.Exit += this.Application_Exit;
            this.UnhandledException += this.Application_UnhandledException;
            
            InitializeComponent();

            bool registerResult = WebRequest.RegisterPrefix(
              "WCF Address", System.Net.Browser.WebRequestCreator.ClientHttp);


        }

        private void Application_Startup(object sender, StartupEventArgs e)
        {
           // System.Threading.Thread.CurrentThread.CurrentUICulture = System.Threading.Thread.CurrentThread.CurrentCulture;
            CultureInfo culture = new CultureInfo("zh-CN");
            Thread.CurrentThread.CurrentCulture = culture;
            Thread.CurrentThread.CurrentUICulture = culture; 
            

            MainPage root = new MainPage(e.InitParams);
            MessageBox.Visibility = Visibility.Collapsed;
            root.ContentGrid.Children.Add(MessageBox);
            this.RootVisual = root;
                       
        }

        private void Application_Exit(object sender, EventArgs e)
        {
            CurrentUser = null;
            try
            {
                ServiceInstance.PublicInforClient.CloseCompleted += (s, ex) =>
                    {
                    };
                ServiceInstance.PublicInforClient.CloseAsync();
                ServiceInstance.QueryClient.CloseCompleted += (s, ex) =>
                {
                };
                ServiceInstance.QueryClient.CloseAsync();

                ServiceInstance.UserClient.CloseCompleted += (s, ex) =>
                {
                };
                ServiceInstance.UserClient.CloseAsync();

                ServiceInstance.AdviseClient.CloseCompleted += (s, ex) =>
                    {

                    };
                ServiceInstance.AdviseClient.CloseAsync();

                
            }
            catch
            {

            }
        }
        private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            // 如果应用程序是在调试器外运行的，则使用浏览器的
            // 异常机制报告该异常。在 IE 上，将在状态栏中用一个 
            // 黄色警报图标来显示该异常，而 Firefox 则会显示一个脚本错误。
            
            if (!System.Diagnostics.Debugger.IsAttached)
            {

                // 注意: 这使应用程序可以在已引发异常但尚未处理该异常的情况下
                // 继续运行。 
                // 对于生产应用程序，此错误处理应替换为向网站报告错误
                // 并停止应用程序。
                e.Handled = true;
                Deployment.Current.Dispatcher.BeginInvoke(delegate { ReportErrorToDOM(e); });
            }

       

        }
        private void ReportErrorToDOM(ApplicationUnhandledExceptionEventArgs e)
        {
            try
            {
                string errorMsg = e.ExceptionObject.Message + e.ExceptionObject.StackTrace;
                errorMsg = errorMsg.Replace('"', '\'').Replace("\r\n", @"\n");

                System.Windows.Browser.HtmlPage.Window.Eval("throw new Error(\"Unhandled Error in Silverlight Application " + errorMsg + "\");");
            }
            catch (Exception)
            {
            }
        }

        public static Regex IDRegex = new Regex(@"^\[(?<ID>\d+)\].*$");
        public static Regex PhoneRegex = new Regex(@"^1\d{10}$");
        public static int GetID(string IDAndName)
        {
            
            if (! App.IDRegex.IsMatch(IDAndName))
            {
                return -1;
            }
            return int.Parse(App.IDRegex.Match(IDAndName).Result("${ID}").Trim());
        }

        /// <summary>
        /// 返回当前用户是否有指定的权限
        /// </summary>
        /// <param name="ID"></param>
        /// <returns>ture，当包含指标权限或者有超级权限;否则，false</returns>
        public static bool IsAuth(int ID)
        {
            if (App.CurrentUser == null) return false;

            return App.CurrentUser.Auths.Contains(1) || App.CurrentUser.Auths.Contains(ID);
        }
        /// <summary>
        /// 返回当前用户是否有指定的权限
        /// </summary>
        /// <param name="ID"></param>
        /// <returns>ture，当包含指标权限且不含超级权限;否则，false</returns>
        public static bool IsAuthOnly(int ID)
        {
            if (App.CurrentUser == null) return false;
            if (!App.CurrentUser.Auths.Contains(1) && App.CurrentUser.Auths.Contains(ID)) return true;

            return false;
        }
        /// <summary>
        /// 返回当前用户是否有指定的权限
        /// </summary>
        /// <param name="StartID"></param>
        /// <param name="EndID"></param>
        /// <returns>ture，当包含指标权限之间或者有超级权限;否则，false</returns>
        public static bool IsAuth(int StartID,int EndID)
        {
            if (App.CurrentUser == null) return false;
            var query = from q in App.CurrentUser.Auths
                        where (q >= StartID && q<=EndID)|| q==1                        
                        select q;
            if (query.Any()) return true;

            return false;
        }

        public static string GetAbsoluteUri(string inUrl)
        {
            Uri uri = null;
            string rtn;
            if (Uri.TryCreate(Application.Current.Host.Source, inUrl, out uri))
            {
                rtn = uri.AbsoluteUri.ToString();
            }
            else
            {
                rtn = inUrl;
            }
            return rtn;
        }


    }
}
